/*
esp8266
NodeMCU 打开/关闭LED
2021-09-12
*/

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>

ESP8266WiFiMulti wifiMulti;

ESP8266WebServer esp8266_server(80); // 网络服务器http服务器对象，端口80

void setup()
{
  Serial.begin(9600);       // 启动中口
  pinMode(LED_BUILTIN, OUTPUT); // 设置LED为输出模式
  
  wifiMulti.addAP("TPLeeSZ","2021#@Lee.com"); // 通过addAP添加wifi密码记录
  wifiMulti.addAP("TPLee","Lee@811212");
  wifiMulti.addAP("TPLee2","Lee@811212");
  
  Serial.print("Connecting ... ");
  int i = 0;
  while(wifiMulti.run() != WL_CONNECTED) // wifiMulti.run()是重点，通过wifi环境中搜索addAP函数所存储的WiFi，成功为WL_CONNECTED
  {
    delay(1000);    // 1秒重试1次
    Serial.print(".");  
  }

  Serial.println("\n");
  Serial.print("Connected to "); // 连接成功
  Serial.println(WiFi.SSID());    // 连接的wifi名称
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP()); // 返回NodeMCU的IP地址

  // 启动网络服务功能
  esp8266_server.begin();
  esp8266_server.on("/", handleRoot);       // 根路径响应
  esp8266_server.on("/LED",HTTP_POST, handleLED); // LED路径响应处理
  esp8266_server.onNotFound(handleNoFound); // 404响应
  Serial.println("HTTP esp8266_server started");
}

void handleRoot() // 处理网站根目录访问
{
  bool isOn = !digitalRead(LED_BUILTIN); // LOW亮，HIGH灭
  char colors[2][8] = {"#D1761A","#49999d"};
  char content[180];      
  sprintf(content, "<form action=\"/LED\" method=\"POST\"><input type=\"submit\" value=\"Toggle LED\" style=\"color: #ffffff;width: 120px;height: 28px;border-radius: 10px;border: none;background-color:%s\" ></form>",colors[isOn]);
  esp8266_server.send(200, "text/html;charset=UTF-8", content);
}

void handleNoFound() // 处理 404访问
{
  esp8266_server.send(404, "text/plain", "The page not found!(from ESP8266)");
}

void handleLED() // 处理LED切换按钮提交
{
  Serial.println("LED POST");
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // 改变LED亮/灭状态
  esp8266_server.sendHeader("Location", "/"); // 跳转回页面根目录
  esp8266_server.send(303); // 发送http相应代码303跳转
}

void loop()
{
  esp8266_server.handleClient(); // 处理http服务访问
}
